package com.niuniu.rushdorm.util;

import com.niuniu.rushdorm.pojo.vo.UserVO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import java.nio.charset.StandardCharsets;
import java.security.Key;

/**
 * @author Meng
 * 2022/11/9
 */
public class JwtUtils {
    //TODO 从配置中读取密钥
    private static final Key key = Keys.hmacShaKeyFor("faetsixrrggferqe5efffghergaefwvferer".getBytes(StandardCharsets.UTF_8));
    public static String generateToken(Long uid,String tokenId,Integer refreshCount){
        String token = Jwts.builder()
                .claim("uid",uid)
                .claim("token_id",tokenId)
                .claim("refresh_count",refreshCount)
                .signWith(key).compact();
        return token;
    }
    public static String generateToken(Long uid, String tokenId, Integer refreshCount, UserVO userVO){
        String token = Jwts.builder()
                .claim("uid",uid)
                .claim("token_id",tokenId)
                .claim("refresh_count",refreshCount)
                .claim("user",JsonUtils.toJsonString(userVO))
                .signWith(key).compact();
        return token;
    }
    public static UserVO getUserVO(String jws){
        String st = getClaims(jws).get("user",String.class);
        return JsonUtils.parseObject(st,UserVO.class);
    }
    public static Claims getClaims(String jws) throws SignatureException{
        Claims claims = null;
        claims =  Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jws).getBody();
        return claims;
    }
}
